
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
from rest_framework.response import Response
from .serializers import *


from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated,AllowAny
from rest_framework.throttling import ScopedRateThrottle
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination

class MyPage(PageNumberPagination):
    page_size = 5 # 默认指定每页几个划分
    max_page_size = 10 # 最多每页10个划分
    page_query_param = 'page' # 查询字符串参数"?page=1"
    page_size_query_param = 'page_size' # 查询字符串参数"?page_size=10"


class MyOffset(LimitOffsetPagination):
    max_limit = 10 # 分页的最大每页数量
    limit_query_param = 'limit' # 查询字符串参数"?limit=5"指定请求的每页数量
    offset_query_param = "offset" # 查询字符串参数"?offset=3"指定请求的偏移量
    default_limit = 5 # 默认每页数量

# 书本增删改查
class BooksView(ModelViewSet):
    """
    list:
    返回图书列表数据

    create:
    新建一本图书
    """

    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializer

    # 指定当前视图使用的身份认证后端; 局部配置隐藏全局
    authentication_classes = [SessionAuthentication]
    # 指定当前视图使用的权限检查后端；局部配置隐藏全局
    permission_classes = [AllowAny]

    # 指定当前视图使用的限流后端；局部配置隐藏全局
    # throttle_classes = [ScopedRateThrottle]
    # 指定限流频次
    # throttle_scope = 'books_rate' # 2/day

    # 指定当前视图的过滤后端；局部隐藏全局
    # filter_backends = [OrderingFilter, DjangoFilterBackend]

    # 可依据的过滤字段
    filterset_fields = ['bread', 'bcomment', 'btitle', 'is_delete']
    # 可依据的排序字段
    ordering_fields = ['bread', 'bcomment', 'bpub_date']

    @action(methods=['get'], detail=False)
    def latest(self, request):

        a = 10 / 0 # ZeroDevitionError异常，是python的基本异常，非DRF异常,DRF框架默认无法捕获！
        # raise serializers.ValidationError("故意抛出的DRF异常！") # DRF异常，DRF框架可以捕获并构造响应！

        book = BookInfo.objects.latest('bpub_date')
        serializer = BookInfoModelSerializer(instance=book)
        return Response(serializer.data)


# 英雄增删改查
class HerosView(ModelViewSet):
    queryset = HeroInfo.objects.all()
    serializer_class = HeroInfoModelSerializer

    # throttle_scope = 'heros_rate' # 5/day

    # 指定当前视图使用的分页后端
    # pagination_class = MyPage
    pagination_class = MyOffset


